/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.dialogos;

import org.grupoavatar.guiaubicua.R;
import org.grupoavatar.guiaubicua.VDownloading;
import org.grupoavatar.guiaubicua.VInicial;
import org.grupoavatar.guiaubicua.mix.DataView;
import org.grupoavatar.guiaubicua.mix.Marker;
import org.grupoavatar.guiaubicua.mix.MixContext;
import org.grupoavatar.guiaubicua.mix.gui.PaintScreen;
import org.grupoavatar.guiaubicua.punto.MasterActivity;
import org.grupoavatar.guiaubicua.auxiliares.Utiles;
import org.grupoavatar.guiaubicua.dialogos.POI_Locked_Actions;
import org.grupoavatar.guiaubicua.entidades.ARMarker;
import org.grupoavatar.guiaubicua.gestores.GestorConfiguracion;

import com.handlerexploit.prime.utils.ImageManager;
import com.handlerexploit.prime.utils.ImageManager.ExtendedRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class POI_Locked_Dialog extends Dialog {
        
        Activity mActivity;        

        public POI_Locked_Dialog(final Marker marker,final Context context/*,  final MixContext ctx, final MixState state*/) {        
                super(context,android.R.style.Theme_Translucent_NoTitleBar);        		
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                
                
                
                PaintScreen dw = GestorConfiguracion.dWindow;
                setContentView(R.layout.poi_locked_dialog);
                
                TextView txtTitle = (TextView)findViewById(R.id.txtTitle);
                txtTitle.setText(marker.distanciaInmediata());
                
                
                TextView textcategoria = (TextView) this.findViewById(R.id.categoria);
                textcategoria.setText(MixContext.getDataSourceName(marker.getDatasource()));
                //marker.getDatasource()
                ImageView imageCate = (ImageView) this.findViewById(R.id.imagen_categoria);
                Bitmap bitfile_cate = ((ARMarker)marker).getDataSourceCircleIconRA(this.getContext().getResources());                
  
                imageCate.setImageBitmap(bitfile_cate);               
                
                TextView textdescription = (TextView) this.findViewById(R.id.descripcion_corta);
                textdescription.setText(((ARMarker)marker).getDes_Corta());
                //textdescription.setText("hola");
                
                //CAMBIOS PARA FOTOS
                if (((ARMarker)marker).getUrlImgs().size() > 0) {
	                final String imageURL = ((ARMarker)marker).getUrlImgs().get(0);
					
					LayoutInflater inflater = (LayoutInflater)VInicial.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					final LinearLayout linImg = new LinearLayout(VInicial.getContext());
					inflater.inflate(R.layout.img_locked_poi, linImg);
					
					ARPUCPRemoteImageView remoteImageView = new ARPUCPRemoteImageView(VInicial.getContext(), linImg);
					
					//remoteImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 125));
					remoteImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					remoteImageView.setScaleType(ScaleType.FIT_CENTER);
					remoteImageView.setAdjustViewBounds(true);
					// padding right a todas menos la ultima imagen
					remoteImageView.setId(0);
			    	remoteImageView.setImageURL(imageURL);
			    	
			    	linImg.addView(remoteImageView);
	
					LinearLayout linlayPoiImgs = (LinearLayout) findViewById(R.id.linlayPoiImg);
					linlayPoiImgs.addView(linImg);
                }
                //FIN CAMBIOS PARA FOTO
                /*
                ImageView image = (ImageView) this.findViewById(R.id.foto_miniatura);
                
                                        
                //String ruta_imagen = "/sdcard/guiaUbicuaPUCP/fotos_miniatura/1.jpg"; //La siguiente línea reemplazo a la anterior
                String ruta_imagen =Environment.getExternalStorageDirectory().getPath()+"/guiaUbicuaPUCP/fotos_miniatura/1.jpg";
                
                Bitmap bitfile = BitmapFactory.decodeFile(ruta_imagen);
                        
                image.setImageBitmap(bitfile);                
                */
                
                Window window = this.getWindow();
                window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                		WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
                
                WindowManager.LayoutParams WMLP = this.getWindow().getAttributes();
                //WMLP.x = (int) -dw.getWidth()/2;   //x position               
                WMLP.y = (int) dw.getHeight()*2/5;   //y position                       		
                //WMLP.width = (int) dw.getWidth();
                if (Utiles.isTablet(context)) {
                	WMLP.width = 600; 
                	WMLP.height = 150;
                } 
                	else
                {
                	WMLP.width = (int) dw.getWidth();
                	WMLP.height = (int) dw.getHeight()*2/5;
                }
                                
                
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                System.out.println((int) dw.getWidth());
                
                this.getWindow().setAttributes(WMLP);
                this.setCancelable(true);     
                //this.setCanceledOnTouchOutside(true);
                this.show();
                
                // mActivity = activity;
                mActivity = GestorConfiguracion.activity;
                
                TextView closeButton = (TextView) this.findViewById(R.id.Cerrar);
                closeButton.setOnClickListener(new View.OnClickListener() {      
                       public void onClick(View view) { 
                           dismiss();     
                       } 
                });

                Button detalles = (Button) this.findViewById(R.id.detalles);
                detalles.setOnClickListener(new Button.OnClickListener() {      
                       public void onClick(View view) {                     
                    	   /*
                           boolean evtHandled = false;
                           evtHandled = state.handleEvent(ctx, marker);
                           */
                    	   if (DataView.viendoUnicoMarker) {
                    		   mActivity.finish();
                    		   //dismiss();
                    	   } else {
	                    	   Intent i = new Intent(VInicial.getContext(), VDownloading.class);
	       					   i.putExtra("sigV", "poi");
	       					   //VPOI.setPoi((ArpucpPOIMarker) marker);
//	       					   TabGeneral.setPoi((ArpucpPOIMarker) marker);
//	       					   TabUbicacion.setPoi((ArpucpPOIMarker) marker);
//	       					   TabServicios.setPoi((ArpucpPOIMarker) marker);
	       					   //MasterActivity.addPoi((ArpucpPOIMarker)marker);
	       					   MasterActivity._poi = (ARMarker)marker;
	       					   MasterActivity._markerListTemporal = VInicial.dataView.getDataHandler().getMarkerList();
	       					   MasterActivity._bpoi = null;
	       					   MasterActivity._poiHijoAnterior = null;
	       					   i.putExtra("idPOI", "setted");
	       					   mActivity.startActivity(i);
                    	   }
                       }
                });
                Button acciones = (Button) this.findViewById(R.id.acciones);
                acciones.setOnClickListener(new Button.OnClickListener() {
                	public void onClick(View view) {
     		    	   new POI_Locked_Actions(context,marker,mActivity/*,ctx,state*/);
                	}
                });                    
        }     
        
        public void onWindowFocusChanged(boolean hasFocus) {
    		// TODO Auto-generated method stub
    		super.onWindowFocusChanged(hasFocus);
    		//Here you can get the size!
    		LinearLayout linlayPoiImg = (LinearLayout) findViewById(R.id.linlayPoiImg);
    		int height = linlayPoiImg.getHeight();
    		int width = linlayPoiImg.getWidth();
			if (height > 0 && ((width*1.0/height) > 0.4)) {
				linlayPoiImg.getLayoutParams().width = height;
			}
    	}
        
}

class ARPUCPRemoteImageView extends ImageView {

    private ImageManager mImageManager;
    private LinearLayout linImg;

    private String mImageURL;

    public ARPUCPRemoteImageView(Context context) {
        super(context);
        setup(context, null, 0);        
    }

    public ARPUCPRemoteImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup(context, attrs, 0);
    }

    public ARPUCPRemoteImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setup(context, attrs, defStyle);
    }

    public ARPUCPRemoteImageView(MixContext context, LinearLayout linImg) {
        super(context);
        setup(context, null, 0);
        this.linImg = linImg;
	}

	private void setup(Context context, AttributeSet attrs, int defStyle) {
        mImageManager = ImageManager.getInstance(context);
    }

    /**
     * Sets the content of this ImageView to the specified URL.
     * 
     * @param source
     *            The URL of a remote image
     */
    public void setImageURL(String source) {
        if (source != null) {
            mImageURL = source;
            mImageManager.get(mExtendedRequest);
        }
    }

    private ExtendedRequest mExtendedRequest = new ExtendedRequest() {

        @Override
        public void onImageReceived(String source, Bitmap bitmap) {
            if (mImageURL != null && mImageURL.equals(source) && bitmap != null) {
                setImageBitmap(bitmap);
		    	ProgressBar p = (ProgressBar) linImg.findViewById(R.id.pgbDownloadingPoiImage);
		    	p.setVisibility(View.GONE);
            }
        }

        @Override
        public String getSource() {
            return mImageURL;
        }

        @Override
        public Bitmap onPreProcess(Bitmap raw) {
            return raw;
        }

        @Override
        public int getHeight() {
            return ARPUCPRemoteImageView.this.getHeight();
        }

        @Override
        public int getWidth() {
            return ARPUCPRemoteImageView.this.getWidth();
        }
    };
}